package com.eboss2.sbs.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.eboss2.sbs.R;
import com.eboss2.sbs.activity.base.BaseActivity;
import com.eboss2.sbs.config.Config;
import com.eboss2.sbs.http.HttpUtil;
import com.eboss2.sbs.model.TicektResponse;
import com.eboss2.sbs.myapplication.MyApplication;
import com.eboss2.sbs.weight.NumberKeyboardDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.mytools.tool.views.MyDialog;
import com.tool.utils.utils.StringUtils;
import com.tool.utils.utils.ToastUtils;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import org.json.JSONObject;


public class VerificationActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "VerificationActivity";
    private LinearLayout ll;
    private LinearLayout ll0;
    private RelativeLayout rlCardNo;
//    private TextView tType;
    private TextView tName;
    private TextView tOldPrice;
    private TextView tPayPrice;
//    private TextView tGet;
    private TextView tStatus;
    private TextView tvCard;
//    private EditText tNo;
//    private int status;

    private Button id_sure;
    private Button id_cz;

//    private NumKeyView mKeyView;
//    private PopupWindow mPop;
//    private View mPopView;

    private NumberKeyboardDialog numberKeyboardDialog;
    private PopupWindow popupWindow;

    private Handler mHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = this;
        setContentView(R.layout.activity_veriflation);
        setTvText(R.id.tv_title, "验券");
        findViewById(R.id.titleback_btn_back).setOnClickListener(this);
        initView();
        initNumberListener();


        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                numberKeyboardDialog.show(mContext, ll0);
            }
        }, 300);
    }

    @Override
    protected void onStart() {
        super.onStart();

    }

    private void initView() {
        tvCard = textView(R.id.id_ticket_no);
        tvCard.setOnClickListener(this);
        button(R.id.id_sure).setOnClickListener(this);
        button(R.id.id_cz).setOnClickListener(this);
        ll = linearLayout(R.id.id_ll_ticket);
//        tType = textView(R.id.id_ticket_type);
        tName = textView(R.id.id_ticket_name);
        tOldPrice = textView(R.id.id_ticket_old_price);
        tPayPrice = textView(R.id.id_ticket_pay_price);
//        tGet = textView(R.id.id_ticket_get);
        tStatus = textView(R.id.id_ticket_status);

        id_sure = button(R.id.id_sure);
        id_cz = button(R.id.id_cz);

        ll0 = linearLayout(R.id.ll);
        rlCardNo = relativeLayout(R.id.rl_card_num);
        rlCardNo.setOnClickListener(this);

    }

    private void reset(){
        tName.setText("");
        tOldPrice.setText("");
        tPayPrice.setText("");
        tStatus.setText("");
        tvCard.setText("");
        ll.setVisibility(View.GONE);
        numberKeyboardDialog.show(mContext, ll0);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.id_cz:
                if (StringUtils.isEmpty(tvCard.getText().toString().trim())){
                    ToastUtils.CustomShow(this, "请输入券码或扫码");
                    return;
                }
                commitTicketRefund();
                break;
            case R.id.id_sure:
                if (StringUtils.isEmpty(tvCard.getText().toString().trim())){
                    ToastUtils.CustomShow(this, "请输入券码或扫码");
                    return;
                }
                commitTicket();
                break;
            case R.id.titleback_btn_back:
                finish();
                break;
            case R.id.id_ticket_no:
                numberKeyboardDialog.show(mContext, ll0);
                break;
        }
    }

    private void initNumberListener() {
        numberKeyboardDialog = new NumberKeyboardDialog(mContext);
        numberKeyboardDialog.setNumberClickListener(new NumberKeyboardDialog.NumberClickListener() {
            @Override
            public void clickNumber(String number) {
                String roomInput = tvCard.getText().toString();
                tvCard.setText(roomInput + number);
            }

            @Override
            public void clickNumber0(String number0) {
//                String roomInput = tvCard.getText().toString();
                //0不能在第一位
//                if (!TextUtils.isEmpty(roomInput)) {
//                    tvCard.setText(roomInput + number0);
//                }
            }

            @Override
            public void clickClearLast() {
                String roomInput = tvCard.getText().toString();
                if (tvCard.length() > 0) {
                    tvCard.setText(roomInput.substring(0, tvCard.length() - 1));
                }
            }

            @Override
            public void longClickClearLast() {
                tvCard.setText("");
            }

            @Override
            public void clickEnter(PopupWindow mPop) {
                final String roomId = tvCard.getText().toString();
                if (StringUtils.isEmpty(roomId)){
                    ToastUtils.CustomShow(mContext, "请输入券码或扫码");
                    return;
                }
                popupWindow = mPop;
                checkTicket();
            }

            @Override
            public void clickScan(PopupWindow mPop) {
                popupWindow = mPop;
                startActivityForResult(new Intent(VerificationActivity.this, CaptureActivity.class), 1);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case 1:
                String result = data.getExtras().getString(CodeUtils.RESULT_STRING);
                tvCard.setText(result);
                checkTicket();
                break;
            default:
                break;
        }
    }


    private void commitTicketRefund() {

        showProgress("加载中...");
        RequestParams params = new RequestParams();
        params.put("couponCode", tvCard.getText().toString().trim());
        params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        HttpUtil.get(Config.SBS_COUPON_CZ, params, new HttpUtil.RequestListener() {
            @Override
            public void success(String response) {
                disShowProgress();

                try {
                    JSONObject result = new JSONObject(response);

                    if (!result.optBoolean("status")) {
                        MyDialog.Builder builder = new MyDialog.Builder(mContext);
                        builder.setTitle("提示");
                        builder.setMessage(result.optString("message"));
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                            }
                        });
                        builder.create().show();
                    }else {

                        MyDialog.Builder builder = new MyDialog.Builder(mContext);
                        builder.setTitle("提示");
                        builder.setMessage(result.optString("message"));
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                reset();
                            }
                        });
                        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int arg1) {
                                dialog.dismiss();
                                reset();

                            }
                        });
                        builder.create().show();
                    }
                } catch (Exception e) {
                    Log.e(TAG, "doLogin() Exception: " + e.getMessage());
                }


            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });
    }

    private void commitTicket() {

        showProgress("加载中...");
        RequestParams params = new RequestParams();
        params.put("couponCode", tvCard.getText().toString().trim());
        params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        HttpUtil.get(Config.SBS_COUPON_DO, params, new HttpUtil.RequestListener() {
            @Override
            public void success(String response) {
                disShowProgress();
                try {
                    JSONObject result = new JSONObject(response);

                    MyDialog.Builder builder = new MyDialog.Builder(mContext);
                    builder.setTitle("提示");
                    builder.setMessage(result.optString("message"));
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            reset();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int arg1) {
                            dialog.dismiss();
                            reset();

                        }
                    });
                    builder.create().show();
                } catch (Exception e) {
                    Log.e(TAG, "doLogin() Exception: " + e.getMessage());
                }




            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }

    private void checkTicket() {

        showProgress("加载中...");
        RequestParams params = new RequestParams();
        params.put("couponCode", tvCard.getText().toString().trim());
        params.put("sid", MyApplication.getmInstance().getLoginMEntity().getShopid());
        HttpUtil.get(Config.SBS_COUPON_CHECK, params, new HttpUtil.RequestListener() {
            @Override
            public void success(String response) {
                disShowProgress();
                try {
                    JSONObject result = new JSONObject(response);

                    if (!result.optBoolean("status")) {
                        ToastUtils.CustomShow(mContext, result.optString("message"));
                    } else {

                        TicektResponse data =  new Gson().fromJson(result.optString("data"), new TypeToken<TicektResponse>() {
                        }.getType());

                        if (data != null){
                            ll.setVisibility(View.VISIBLE);
                            popupWindow.dismiss();
                            tName.setText(data.getGoodName());
                            /**
                             * 这个地方服务端是反的，所以写反
                             */
                            tPayPrice.setText(StringUtils.formatIntMoney(data.getOldAmount()));
                            tOldPrice.setText(StringUtils.formatIntMoney(data.getPayAmount()));
                            tStatus.setText(data.getStatusName());

                            if (data.getStatus() == 2){
                                id_sure.setVisibility(View.GONE);
                            }else{
                                id_sure.setVisibility(View.VISIBLE);
                            }

                            if (data.isCorrect()){
                                id_cz.setVisibility(View.GONE);
                            }else{
                                id_cz.setVisibility(View.VISIBLE);
                            }
                        }


                    }
                } catch (Exception e) {
                    Log.e(TAG, "doLogin() Exception: " + e.getMessage());
                }


            }

            @Override
            public void failed(Throwable error) {
                disShowProgress();
                showE404();
            }
        });

    }
}
